from models.entity.role import Role
from models.entity.token_with_button import TokenWithButton
from models.entity.role_with_user import RoleWithUser
from models.entity.module import Module
from models.entity.user import User
from models.entity.button import Button
from models.entity.token import Token
from utils.tool import listDuplicateRemoval
from utils.tool import listOrderByItemAttr

from flask import session

# 授权合乎逻辑的模型
class AuthLogicalModel:

    def __init__(self, data):
        if isinstance(data, Token):
            # data为token对象
            self.token = data  # token object
            self.user = User.query.filter_by(id=self.token.user_id).first()  # user object
            self.roles = []  # roles list
            role_connectors = RoleWithUser.query.filter_by(user_id=self.user.id).all()
            for role_connector in role_connectors:
                the_role = Role.query.filter_by(id=role_connector.role_id).first()
                self.roles.append(the_role.to_dict())
            self.buttons = []  # buttons list
            last_level_module = set()
            button_connectors = TokenWithButton.query.filter_by(token_id=self.token.id).all()
            for button_connector in button_connectors:
                the_button = Button.query.filter_by(id=button_connector.button_id).first()
                last_level_module.add(Module.query.filter_by(id=the_button.module_id).first())
                self.buttons.append(the_button.to_dict())
            self.modules = []  # all modules that can be reached
            last_level_module = listOrderByItemAttr(list(last_level_module), "dis_order")
            # print("last_level_module: %s" % str(last_level_module))
            for item in last_level_module:
                node_locations = item.path.split(",")
                for node_location in node_locations:
                    self.modules.append(Module.query.filter_by(id=node_location).first())
            self.modules = listDuplicateRemoval(self.modules)    # 在不改变顺序的情况下去重
            self.modules = listOrderByItemAttr(self.modules, "path")
            # print("modules: %s" % str(self.modules))
            self.module_list = []
            for module in self.modules:
                self.module_list.append(module.to_dict())
            self.urls=[]
            for module in self.modules:
                if module.url != "":
                    self.urls.append(module.url)
            for button in self.buttons:
                if button["url"] != "":
                    self.urls.append(button["url"])
            i = 0
            m = self.modules[0].id
            while i < (len(self.modules)-1):
                if self.modules[i].depth > self.modules[i+1].depth:
                    m = self.modules[i+1].id
                i += 1
            self.modules=Module().get_tree_by_pid(0)[0]["children"]
            # print("module list: %s" % str(self.module_list))
            # print("modules tree: %s" % str(self.modules))
        else:
            self.token = Token.get_token_by_token_str(session["auth"]["token"])
            self.user = User.get_user_by_id(session["auth"]["user_id"])
            self.roles = session["auth"]["roles"]
            self.buttons = session["auth"]["buttons"]
            self.modules = session["auth"]["modules"]
            self.module_list = session["auth"]["module_list"]
            self.urls = session["auth"]["urls"]

    def get_dic(self):
        # 获取此对象的字典表示
        rdic = {}
        print(self.user)
        rdic["token"] = self.token.token
        rdic["user_id"] = self.user.id
        rdic["username"] = self.user.username
        rdic["roles"] = self.roles
        rdic["buttons"] = self.buttons
        rdic["modules"] = self.modules
        rdic["module_list"] = self.module_list
        rdic["urls"] = self.urls
        return rdic

    def update_redis(self):
        # 更新缓存
        self.token = Token.get_token_by_token_str(session["auth"]["token"])  # token object
        self.user = User.query.filter_by(id=self.token.user_id).first()  # user object
        self.roles = []  # roles list
        role_connectors = RoleWithUser.query.filter_by(user_id=self.user.id).all()
        for role_connector in role_connectors:
            the_role = Role.query.filter_by(id=role_connector.role_id).first()
            self.roles.append(the_role.to_dict())
        self.buttons = []  # buttons list
        last_level_module = set()
        button_connectors = TokenWithButton.query.filter_by(token_id=self.token.id).all()
        for button_connector in button_connectors:
            the_button = Button.query.filter_by(id=button_connector.button_id).first()
            last_level_module.add(Module.query.filter_by(id=the_button.module_id).first())
            self.buttons.append(the_button.to_dict())
        self.modules = []  # all modules that can be reached
        last_level_module = listOrderByItemAttr(list(last_level_module), "dis_order")
        for item in last_level_module:
            node_locations = item.path.split(",")
            for node_location in node_locations:
                self.modules.append(Module.query.filter_by(id=node_location).first())
        self.modules = listDuplicateRemoval(self.modules)  # 在不改变顺序的情况下去重
        self.modules = listOrderByItemAttr(self.modules, "path")
        print("modules: %s" % str(self.modules))
        self.module_list = []
        for module in self.modules:
            self.module_list.append(module.to_dict())
        self.urls = []
        for module in self.modules:
            if module.url != "":
                self.urls.append(module.url)
        for button in self.buttons:
            if button["url"] != "":
                self.urls.append(button["url"])
        i = 0
        m = self.modules[0].id
        while i < (len(self.modules) - 1):
            if self.modules[i].depth > self.modules[i + 1].depth:
                m = self.modules[i + 1].id
            i += 1
        self.modules = Module().get_tree_by_pid(0)[0]["children"]
        print("in update_redis"+str(session))
        session["auth"] = self.get_dic()
